#include "control.h"

#include <QDir>
#include <QDebug>

Control::Control(QObject *parent) : QObject(parent)
{
    m_process = new QProcess(this);
    connect(m_process, &QProcess::started, this, [=]() {
        if (m_isServer) {
            qInfo() << "Anti control server started successfully!";
            Q_EMIT sigServerState(true);
        } else {
            qInfo() << "Anti control client started successfully!";
            Q_EMIT sigClientState(true);
        }
    });
    // connect(m_process, &QProcess::errorOccurred, [&](QProcess::ProcessError error) {
    //     if (m_isServer) {
    //         qInfo() << "Anti control server startup error: " << error;
    //         Q_EMIT sigServerState(false);
    //     } else {
    //         qInfo() << "Anti control client startup error: " << error;
    //         Q_EMIT sigClientState(false);
    //     }
    // });
}

Control::~Control()
{
    if (m_process != nullptr) {
        if (m_process->state() == QProcess::Running) {
            m_process->close();
        }
        m_process->deleteLater();
        m_process = nullptr;
    }
}

void Control::startServer()
{
    m_isServer = true;
    QString serverpara = "anti-control-server -f --debug DEBUG --name server --disable-crypto --log " + QDir::homePath()
                         + "/.log/kylin-connectivity-control.log --disable-client-cert-checking"
                           " -c "
                         + "/usr/share/kylin-connectivity/control.conf --address :27194";
    qInfo() << "Anti control server starting...";
    m_process->start(serverpara);
}

void Control::startClient(QString address)
{
    m_isServer = false;
    QString clientpara = "anti-control-client -f --debug DEBUG --name client --disable-crypto --log " + QDir::homePath()
                         + "/.log/kylin-connectivity-control.log"
                           " ["
                         + address + "]:27194 ";
    qInfo() << "Anti control client starting..";
    m_process->start(clientpara);
}